package de.fhkl.android.activities;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.cookie.Cookie;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import de.fhkl.android.R;
import de.fhkl.android.utils.ConnectionManager;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GestureOverlayView;
import android.gesture.Prediction;
import android.gesture.GestureOverlayView.OnGesturePerformedListener;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.TimePicker;
import android.widget.Toast;

public class RoomActivity extends Activity {
	private static final String TAG = "RoomActivity";
	// private static final String HOST = "10.121.4.182:8080";
	private static final String HOST = "172.17.10.56:8080";
	private static final String REFERER = "http://" + HOST + "/raeume/mobile/";
	private static final String ACTION_LOGIN = "DemoLogin.do";
	private static final String ACTION_RAUMSUCHE_VIEW = "Raumsuche.do?method=view";
	private static final String ACTION_LOADOWN = "Reservierungsuebersicht.do?method=loadOwn&reservationID=0&prebookedby=false";
	private static final String ACTION_RAUMSUCHE_STANDORT = "Raumsuche.do?method=standort";
	private List<Cookie> cookies = new ArrayList<Cookie>();
	private NameValuePair JSESSIONID = new BasicNameValuePair("JSESSIONID", "");
	private static String location = "ZW";
	private static String PRTL_UNAME = "schiefer";
	private static String password, lt;

	private GestureOverlayView gestureView;
	private GestureLibrary gestureLib;
	private LinearLayout mainView, naviView, contentView;
	private int count = 3;
	private Button[] buttons;
	private String[] buttonsNames;
	private WebView[] webViews;
	private int activeButtonNum;
	private static int contentViewBgColor = Color.WHITE;
	private static int buttonActiveColor = Color.WHITE;
	private static int buttonInactiveColor = Color.GRAY;
	private static int buttonTextColor = Color.BLACK;

	public void onCreate(Bundle savedInstanceState) {
		Log.i(TAG, "begin");
		super.onCreate(savedInstanceState);
		initiate();
		setContentView(gestureView);

		login();

		initLoadUrl(0);
		initLoadUrl(1);
		initLoadUrl(2);

		Log.i(TAG, "end");
	}

	protected void onDestroy() {
		Log.w(TAG, "onDestroy()");
		super.onDestroy();
	}

	private void login() {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
		nameValuePairs.add(new BasicNameValuePair("PRTL_UNAME", PRTL_UNAME));
		nameValuePairs.add(new BasicNameValuePair("mobile","android"));
		String url = REFERER + ACTION_LOGIN;
		cookies = ConnectionManager.postForCookies(url, nameValuePairs);
		JSESSIONID = ConnectionManager.getCookie(cookies, JSESSIONID.getName());
		Log.e(TAG, JSESSIONID.toString());
	}

	private OnClickListener RoomButtonOnClickListener = new OnClickListener() {
		public void onClick(View button) {
			activeButtonNum = button.getId();
			for (int i = 0; i < buttons.length; i++) {
				if (i == activeButtonNum) {
					buttons[i].setBackgroundColor(buttonActiveColor);
				} else {
					buttons[i].setBackgroundColor(buttonInactiveColor);
				}
			}
			contentView.removeAllViews();
			contentView.addView(webViews[activeButtonNum]);
		}
	};

	private void initiate() {
		initGestureView();
		initButtons();
		initWebViews();
		initMainView();

	}

	private void initGestureView() {
		gestureLib = GestureLibraries
				.fromRawResource(this, R.raw.gestures_main);
		if (!gestureLib.load()) {
			Toast.makeText(this, "Could not load R.raw.gestures_main",
					Toast.LENGTH_SHORT).show();
		}
		gestureView = new GestureOverlayView(this);
		gestureView.setFadeOffset(100);
		gestureView.setGestureVisible(true);
		gestureView.setLayoutParams(new ViewGroup.LayoutParams(
				ViewGroup.LayoutParams.FILL_PARENT,
				ViewGroup.LayoutParams.FILL_PARENT));
		gestureView
				.addOnGesturePerformedListener(new OnGesturePerformedListener() {
					public void onGesturePerformed(GestureOverlayView view,
							Gesture gesture) {

						ArrayList<Prediction> predictions = gestureLib
								.recognize(gesture);
						Log.i("gestureView",
								"onGesturePerformed" + predictions.size());
						if (predictions.size() > 0) {
							Prediction prediction = (Prediction) predictions
									.get(0);
							Log.w("score", prediction.score + "");
							if (prediction.score > 50) {
								if (prediction.name.equals("left")) {
									webViews[activeButtonNum].goBack();
								} else if (prediction.name.equals("right")) {
									webViews[activeButtonNum].goForward();
								}
								// buttons[activeButtonNum].performClick();
							}
						}
					}
				});
	}

	private void initMainView() {
		mainView = new LinearLayout(this);
		mainView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT));
		mainView.setOrientation(LinearLayout.VERTICAL);

		naviView = new LinearLayout(this);
		naviView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT));
		naviView.setOrientation(LinearLayout.HORIZONTAL);
		for (int i = 0; i < buttons.length; i++) {
			buttons[i].setLayoutParams(new LinearLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));
			naviView.addView(buttons[i]);
		}

		mainView.addView(naviView);

		contentView = new LinearLayout(this);
		contentView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT));
		contentView.setOrientation(LinearLayout.VERTICAL);
		contentView.setBackgroundColor(contentViewBgColor);
		contentView.addView(webViews[activeButtonNum]);

		mainView.addView(contentView);
		gestureView.addView(mainView);
	}

	private void initButtons() {
		buttonsNames = this.getResources().getStringArray(
				R.array.room_activity_button_names);
		buttons = new Button[buttonsNames.length];
		for (int i = 0; i < buttons.length; i++) {
			buttons[i] = new Button(this);
			buttons[i].setText(buttonsNames[i]);
			buttons[i].setTextColor(buttonTextColor);
			buttons[i].setId(i);

			if (i == activeButtonNum) {
				buttons[i].setBackgroundColor(buttonActiveColor);
			} else {
				buttons[i].setBackgroundColor(buttonInactiveColor);
			}

			buttons[i].setOnClickListener(RoomButtonOnClickListener);
		}
	}

	private void initWebViews() {
		webViews = new WebView[count];
		for (int i = 0; i < webViews.length; i++) {
			webViews[i] = new WebView(this);
			webViews[i].setId(i);
			webViews[i].setLayoutParams(new LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
			webViews[i].setScrollbarFadingEnabled(true);
			webViews[i].setWebViewClient(myWebViewClient);
			webViews[i].setWebChromeClient(myWebChromeClient);
			webViews[i].getSettings().setJavaScriptEnabled(true);
			webViews[i].getSettings().setBuiltInZoomControls(true);
		}
		webViews[0].addJavascriptInterface(new ProxyBridge(), "ProxyBridge");
	}

	private WebViewClient myWebViewClient = new WebViewClient() {
		public boolean shouldOverrideUrlLoading(final WebView webView,
				final String url) {
			return super.shouldOverrideUrlLoading(webView, url);
		}
	};

	private WebChromeClient myWebChromeClient = new WebChromeClient() {
		@Override
		public boolean onJsConfirm(WebView view, String url, String message,
				final JsResult result) {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					RoomActivity.this);
			builder.setTitle("Confirm");
			builder.setMessage(message);
			builder.setPositiveButton(android.R.string.ok,
					new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							result.confirm();
						}
					});
			builder.setNegativeButton(android.R.string.cancel,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							result.cancel();
						}
					});
			builder.setCancelable(false);
			builder.create();
			builder.show();
			return true;
		};
	};

	private void initLoadUrl(int type) {
		String url = REFERER;
		WebView webView = webViews[type];
		switch (type) {
		case 0:
			url += ACTION_RAUMSUCHE_VIEW;
			webView = webViews[0];
			break;
		case 1:
			url += ACTION_RAUMSUCHE_STANDORT;
			webView = webViews[1];
			break;
		case 2:
			url += ACTION_LOADOWN;
			break;
		}
		WebViewTask task = new WebViewTask();
		task.setContext(this);
		task.setWebView(webView);
		task.setUrl(url);
		task.setCookies(cookies);
		task.execute();
	}

	public class MyWebChromeClient extends WebChromeClient {

	}

	class WebViewTask extends AsyncTask<String, Void, Boolean> {
		ProgressDialog progressDialog;
		WebView webView;
		List<Cookie> cookies;
		Context context;
		String url;
		CookieManager cookieManager;

		public void setWebView(WebView webView) {
			this.webView = webView;
		}

		public void setUrl(String url) {
			this.url = url;
		}

		public void setCookies(List<Cookie> cookies) {
			this.cookies = cookies;
		}

		public void setContext(Context context) {
			this.context = context;
		}

		protected void onPreExecute() {
			CookieSyncManager.createInstance(context);
			cookieManager = CookieManager.getInstance();
			cookieManager.removeSessionCookie();
			super.onPreExecute();
		}

		protected Boolean doInBackground(String... params) {
			SystemClock.sleep(1000);
			return false;
		}

		protected void onPostExecute(Boolean result) {
			if (cookies != null) {
				for (int i = 0; i < cookies.size(); i++) {
					Cookie cookie = cookies.get(i);
					String cookieString = cookie.getName() + "="
							+ cookie.getValue();
					cookieManager.setCookie(REFERER, cookieString);
					Log.i(TAG, cookie.toString());
					// cookieManager.setCookie(REFERER, cookie.toString());
				}
				CookieSyncManager.getInstance().sync();
			}
			WebSettings webSettings = webView.getSettings();
			webSettings.setJavaScriptEnabled(true);
			webSettings.setBuiltInZoomControls(true);
			webView.loadUrl(url);
			Integer.toString(123);
		}
	}

	/**
	 * Interaction between javascript and java If Input Field to set date ist
	 * clicked, Android pop out DatePickerDialog
	 * 
	 * @author Zhuo Xiu
	 * 
	 */
	class ProxyBridge {
		String dateString;
		String timeString;
		String jsonDate;
		String jsonTime;
		DatePickerDialog datePickerDialog;
		TimePickerDialog timePickerDialog;
		Handler handler = new Handler();

		public void getDate() {
			handler.post(new Runnable() {
				public void run() {
					Calendar calendar = Calendar.getInstance();
					datePickerDialog = new DatePickerDialog(RoomActivity.this,
							new OnDateSetListener() {
								public void onDateSet(DatePicker view,
										int year, int monthOfYear,
										int dayOfMonth) {
									try {

										String dayString = Integer
												.toString(dayOfMonth);
										if (dayString.length() == 1) {
											dayString = "0" + dayString;
										}
										String monthString = Integer
												.toString(monthOfYear + 1);
										if (monthString.length() == 1) {
											monthString = "0" + monthString;
										}
										dateString = dayString + "."
												+ monthString + "."
												+ String.valueOf(year);
										JSONObject jsonObj = new JSONObject();
										jsonObj.put("date", dateString);
										jsonDate = jsonObj.toString();
									} catch (JSONException e) {
										Log.e(TAG, e.toString());
									}
									webViews[activeButtonNum]
											.loadUrl("javascript:setDate("
													+ jsonDate + ")");
								}
							}, calendar.get(Calendar.YEAR), calendar
									.get(Calendar.MONTH), calendar
									.get(Calendar.DAY_OF_MONTH));
					datePickerDialog.show();
				}
			});
		}

		public void getTime(final int initialMinute) {
			handler.post(new Runnable() {
				public void run() {
					timePickerDialog = new TimePickerDialog(RoomActivity.this,
							1, new TimePickerDialog.OnTimeSetListener() {
								public void onTimeSet(TimePicker view,
										int hourOfDay, int minute) {
									try {
										String hourOfDayString = Integer
												.toString(hourOfDay);
										if (hourOfDayString.length() == 1) {
											hourOfDayString = "0"
													+ hourOfDayString;
										}
										String minuteString = Integer
												.toString(minute);
										if (minuteString.length() == 1) {
											minuteString = "0" + minuteString;
										}
										timeString = hourOfDayString + ":"
												+ minuteString;
										JSONObject jsonObj = new JSONObject();
										jsonObj.put("time", timeString);
										jsonObj.put("hour", hourOfDay);
										jsonObj.put("minute", minute);
										jsonTime = jsonObj.toString();
										Log.e(TAG, jsonObj.toString());
									} catch (JSONException e) {
										Log.e(TAG, e.toString());
									}
									webViews[activeButtonNum]
											.loadUrl("javascript:setTime("
													+ jsonTime + ")");
								}
							}, 7, initialMinute, true);
					timePickerDialog.show();
				}
			});
		}
	}

}